import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import 'watermark.dart';

/**
 * @Description: 水印工具类
 * @Author: 下雨了
 * @CreateDate: 2022-07-28 16:10
 * @UpdateUser: 更新者
 * @UpdateDate:  2022-07-28 16:10
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */

///
class WatermarkUtils {
  // 私有构造函数
  WatermarkUtils._internal();

  // 保存单例
  static WatermarkUtils _watermarkUtils = WatermarkUtils._internal();

  // 工厂构造函数
  factory WatermarkUtils() => _watermarkUtils;


  OverlayEntry? _overlayEntry;

  RxBool isShow = true.obs;

  /// 添加默认水印
  ///
  /// [watermark] 水印文案
  /// [rowCount] 水印文案每行显示的个数
  /// [columnCount] 水印文案每列显示的个数
  /// [textStyle] 水印文案的样式
  void addWatermark(BuildContext context,
      String watermark, {
        int rowCount = 3,
        int columnCount = 6,
        TextStyle? textStyle,
      }) async {
    if (_overlayEntry != null) {
      _overlayEntry!.remove();
    }
    OverlayState? overlayState = Overlay.of(context);

    // 需要等父组件创建完成后再去创建小组件
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _overlayEntry = OverlayEntry(
        builder: (context) =>
            Obx(() {
              return isShow.value ? Watermark(
                rowCount: rowCount,
                columnCount: columnCount,
                text: watermark,
                textStyle: textStyle ??
                    TextStyle(
                        color: Color(0x08000000),
                        fontSize: 18.sp,
                        decoration: TextDecoration.none),
              ) : SizedBox();
            }),
      );
      overlayState?.insert(_overlayEntry!);
    });
  }

  /// 添加自定义水印。将[widget]覆盖在所有视图的最上层
  void addCustomWatermark(BuildContext context, Widget widget) {
    if (_overlayEntry != null) {
      _overlayEntry!.remove();
    }
    OverlayState? overlayState = Overlay.of(context);
    _overlayEntry = OverlayEntry(builder: (context) => widget);
    overlayState?.insert(_overlayEntry!);
  }

  /// 移除水印
  void removeWatermark() async {
    if (_overlayEntry != null) {
      _overlayEntry?.remove();
      _overlayEntry = null;
    }
  }

  /// 隐藏水印
  void hide() {
    if (_overlayEntry != null) {
      isShow.value = false;
    }
  }

  /// 显示水印
  void show() {
    if (_overlayEntry != null) {
      isShow.value = true;
    }
  }

}
